package com.hp.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.lang.reflect.Method;

public class SpringElUtil {

    private static final ParameterNameDiscoverer NAME_DISCOVERER = new DefaultParameterNameDiscoverer();
    private static final ExpressionParser PARSER = new SpelExpressionParser();

    /**
     * 支持 #p0 参数索引的表达式解析
     *
     * @param key    表达式
     * @param object 代理对象
     * @param method 目标方法
     * @param args   方法入参
     */
    public static String parse(String key, Object object, Method method, Object[] args) {
        if (StringUtils.isBlank(key)) {
            return "";
        }
        if (ArrayUtils.isEmpty(args)) {
            return key;
        }
        EvaluationContext context = new MethodBasedEvaluationContext(object, method, args, NAME_DISCOVERER);
        return PARSER.parseExpression(key).getValue(context, String.class);
    }
}